package com.runachina.temcollector;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.runachina.R;
import com.runachina.common.BaseActivity;
import com.runachina.common.CompanyActivity;
import com.runachina.java.SendDataAnalysis;
import com.runachina.java.TcpSocket;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 温度采集器  修改表号
 */
public class TemModifyNumActivity extends BaseActivity {

    private Button readnum, setnum;
    private TextView sendtitle, sendtext;
    public static TextView rcvtext, rcvbyte;
    public static EditText oldnum, newnum;

    //读地址
    private static byte[] read_bytes = {(byte) 0xfe, (byte) 0xfe, (byte) 0xfe, 0x68, (byte) 0x50,//类型0x50
            (byte) 0xAA, (byte) 0xAA, (byte) 0xAA, (byte) 0xAA,//表号
            (byte) 0xAA, (byte) 0xAA, (byte) 0xAA,
            0x03, 0x03, (byte) 0x3D, (byte) 0xB4, 0x33,
            (byte) 0x00, 0x16,
            (byte) 0x00, 0x16};

    //修改地址
    public static byte[] modifyNum = {(byte) 0xfe, (byte) 0xfe, (byte) 0xfe, (byte) 0xfe, (byte) 0xfe,
            0x68, (byte) 0x50,
            (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,//错误表号
            0x00, 0x11, 0x11,
            0x15, 0x0A, 0x4B, (byte) 0xD3, (byte) 0x33,//命令
            (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,//正确表号
            0x33, 0x44, 0x44,
            (byte) 0x15, 0x16,
            (byte) 0x00, 0x16};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_temcoll_modifynum);
        //set_flags();
        set_toolbar("修改表号", "");
        set_leftmenuTemColl(TemModifyNumActivity.this);
        init_view();
        hideSendText(sendtitle, sendtext);
        //inWhichAc = "runavalue.ModifyNumActivity";
    }


    /**
     * 初始化界面控件
     */
    void init_view() {
        oldnum = (EditText) findViewById(R.id.oldnum);
        newnum = (EditText) findViewById(R.id.newnum);

        readnum = (Button) findViewById(R.id.readnum);
        readnum.setOnClickListener(readnumFun);
        setnum = (Button) findViewById(R.id.setnum);
        setnum.setOnClickListener(setnumFun);

        sendtitle = (TextView) findViewById(R.id.sendtitle);
        sendtext = (TextView) findViewById(R.id.sendtext);
        rcvtext = (TextView) findViewById(R.id.rcvtext);
        rcvbyte = (TextView) findViewById(R.id.rcvbyte);
    }

    public void clear_textDisplay() {
        sendtext.setText("");
        rcvtext.setText("");
        rcvbyte.setText("");
    }

    /**
     * 读取表号按键响应事件：（其实是抄表协议）
     */
    View.OnClickListener readnumFun = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            clear_textDisplay();
            startTimer(TI);
            //in which Activity
            // inWhichAc = "runavalue.DataResetAvtivity";
            inWhichAc = "temcollector.TemModifyNumActivity.read";
            //获取完整的发送sendbyte[]
            String oldnumStr = oldnum.getText().toString();
            byte[] sendbyte = SendDataAnalysis.temDataReset(read_bytes, oldnumStr, 5, 3);//5：表号起始位置，3：报文校验和起始位置
            //显示完整的发送sendbyte[]
            sendtext.setText(byteToHexString(sendbyte));
            //发送sendbyte[]
            String sendResult = TcpSocket.wifiSendByte(sendbyte);
            //sendtext.setText("发送状态:"+sendResult);

        }
    };

    /**
     * 设置表号按键响应事件：
     */
    View.OnClickListener setnumFun = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            clear_textDisplay();
            //flag
            inWhichAc = "temcollector.TemModifyNumActivity.set";
            //获取完整的发送sendbyte[]
            String oldnumStr = oldnum.getText().toString();
            String newnumStr = newnum.getText().toString();
            if ((oldnumStr.length() == 8) && (newnumStr.length() == 8)) {
                startTimer(TI);
                byte[] sendbyte = SendDataAnalysis.temModifyNum(modifyNum, oldnumStr, newnumStr);
                //显示发送报文
                sendtext.setText(byteToHexString(sendbyte));
                //发送sendbyte[]
                String sendResult = TcpSocket.wifiSendByte(sendbyte);

            } else {
                show("表号错误!");
            }
        }
    };


    /**
     * Toolbar中的Menu菜单项
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    /**
     * Activity创建时候会执行一次，所以可以用来初始化toolbar中的wifi图标
     *
     * @return
     */
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);

        MenuItem menuItem = menu.findItem(R.id.menu_connect);
        //wifi connect，返回当前连接状态
        String connectResult = TcpSocket.readConnect();
        if ((connectResult.equals("连接成功!")) || connectResult.equals("已经连接!")) {
            menuItem.setTitle("connect!");
            menuItem.setIcon(R.drawable.wifi_connect);
        } else {
            menuItem.setTitle("no connect!");
            menuItem.setIcon(R.drawable.wifi_noconnect);
        }
        return true;
    }

    private MenuItem me;
    private int type = 0;

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        me = item;
        System.out.println("onOptionsItemSelected");

        switch (item.getItemId()) {
            case R.id.menu_connect:
                String connectResult = TcpSocket.wificonnect();//wifi connect
                show(connectResult);//TOast connect result
                if ((connectResult.equals("连接成功!")) || connectResult.equals("已经连接!")) {
                    item.setTitle("connect!");
                    item.setIcon(R.drawable.wifi_connect);
                } else {
                    item.setTitle("no connect!");
                    item.setIcon(R.drawable.wifi_noconnect);
                    new Timer().schedule(new TimerTask() {
                        @Override
                        public void run() {
                            goWifiSetting();
                            type = 1;
                        }
                    }, 1000);
                }
                return true;
            case R.id.menu_choice:
                intent = new Intent(TemModifyNumActivity.this, CompanyActivity.class);
                startActivity(intent);
                finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    //每次进来判断是否是从设置wifi页面进来的，如果是，重新连接socket，判断是否可用
    @Override
    protected void onResume() {
        super.onResume();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                type = 0;
                String connectResult = TcpSocket.wificonnect();//wifi connect
                //show(connectResult);//TOast connect result
                if (isWifi()) {
                    if (me != null) {
                        if ((connectResult.equals("连接成功!")) || connectResult.equals("已经连接!")) {

                            me.setTitle("connect!");
                            me.setIcon(R.drawable.wifi_connect);
                        } else {

                            me.setTitle("no connect!");
                            me.setIcon(R.drawable.wifi_noconnect);
                        }
                    }
                } else {
                    if (me != null) {
                        me.setTitle("no connect!");
                        me.setIcon(R.drawable.wifi_noconnect);
                    }

                }
            }
        });

//        Looper.prepare();
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                type=0;
//                String connectResult = TcpSocket.wificonnect();//wifi connect
//                show(connectResult);//TOast connect result
//                if (me!=null){
//                    if ((connectResult.equals("连接成功!")) || connectResult.equals("已经连接!")) {
//                        me.setTitle("connect!");
//                        me.setIcon(R.drawable.wifi_connect);
//                    } else {
//                        me.setTitle("no connect!");
//                        me.setIcon(R.drawable.wifi_noconnect);
//                    }
//                }
//            }
//        }).start();
//Looper.loop();
//        if (type==1){
//            type=0;
//            String connectResult = TcpSocket.wificonnect();//wifi connect
//            show(connectResult);//TOast connect result
//            if (me!=null){
//                if ((connectResult.equals("连接成功!")) || connectResult.equals("已经连接!")) {
//                    me.setTitle("connect!");
//                    me.setIcon(R.drawable.wifi_connect);
//                } else {
//                    me.setTitle("no connect!");
//                    me.setIcon(R.drawable.wifi_noconnect);
//                }
//            }
//        }
    }

    /**
     * 设置back监听
     */
    @Override
    public void onBackPressed() {
        exitApp();
    }
}
